<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
/* 
 公共函数
*/

if (!function_exists('build_ranstr')) {
    /**
     * 获得随机字符串
     * @param   Number  $len    需要的长度
     * @param   Bool    $special    是否需要特殊符号
     * @return  String  返回随机字符串
     */
    function build_ranstr($len = 8, $special = false)
    {
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );

        if ($special) {
            $chars = array_merge($chars, array(
                "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
                "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
                "}", "<", ">", "~", "+", "=", ",", "."
            ));
        }

        $charsLen = count($chars) - 1;
        shuffle($chars);                            //打乱数组顺序
        $str = '';
        for ($i = 0; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $charsLen)];    //随机取出一位
        }
        return $str;
    }
}

if (!function_exists('error')) {
    /**
     * 操作错误跳转的快捷方法
     * @param mixed  $msg    提示信息
     * @param string $url    跳转的 URL 地址
     * @param mixed  $data   返回的数据
     * @return void
     */
    function error($msg = '', $data = null)
    {
        $result = [
            'code' => 0,
            'msg'  => $msg,
            'data' => $data
        ];

        return json_encode($result);
    }
}

if (!function_exists('success')) {
    /**
     * 操作成功跳转的快捷方法
     * @param mixed  $msg    提示信息
     * @param string $url    跳转的 URL 地址
     * @param mixed  $data   返回的数据
     * @return void
     */
    function success($msg = '', $data = null)
    {
        $result = [
            'code' => 1,
            'msg'  => $msg,
            'data' => $data
        ];

        return json_encode($result);
    }
}

if (!function_exists('upload')) {
    /**
     * 单文件上传
     * @param $name             表单图片名称
     */
    function upload($name, Request $request)
    {
        // 自定义返回数据
        $data = [
            'code' => 0,
            'msg' => ''
        ];

        // 获取表单上传文件 例如上传了001.jpg
        $file = $request->file($name);

        if ($file->isValid()) {

            //获取文件的扩展名 
            $ext = $file->getClientOriginalExtension();

            //获取文件的绝对路径
            $path = $file->getRealPath();

            //定义文件名  
            $filename =  date('Ymdhis') . \Illuminate\Support\Str::random(10) . '.' . $ext;

            //存储文件。disk里面的public。总的来说，就是调用disk模块里的public配置
            $path = Storage::disk('uploads')->put($filename, file_get_contents($path));

            if ($path) {
                $data['code'] = 1;
                $data['msg'] = '/uploads/' . $filename;
                return $data;
            } else {
                $data['msg'] = $file->getErrorMessage();
                return $data;
            }
        } else {
            $data['msg'] = "未找到上传的图片";
            return $data;
        }
    }
}

if (!function_exists('build_code')) {
    /**
     * 生成唯一订单号
     *
     * @param string $path 指定的path
     * @return string
     */
    function build_code($prefix = "")
    {
        @date_default_timezone_set("PRC");
        $order_id_main = date('YmdHis') . rand(10000, 99999);
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
        $osn = $prefix . $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT); //生成唯一订单号
        return $osn;
    }
}

// 查询物流接口
if (!function_exists('query_express')) {
    /**
     * $no 快递单号
     * $type 快递公司
     */
    function query_express($no = '', $type = '')
    {
        // 自定义返回数据
        $success = [
            'result' => false,
            'msg' => '',
            'data' => null
        ];

        // 判断单号不能为空
        if (empty($no)) {
            $success['result'] = false;
            $success['msg'] = '快递单号不能为空';
            return $success;
        }

        $data = [
            'no' => $no
        ];

        if (!empty($type)) {
            $data['type'] = $type;
        }

        //url参数结构  http_build_query()函数的作用是使用给出的关联（或下标）数组生成一个经过 URL-encode 的请求字符串。
        $querys = http_build_query($data);

        // header 头信息验证  服务密钥
        $appcode = "填写你自己的AppCode";

        $headers = [
            "Authorization:APPCODE " . $appcode
        ];

        //接口地址 本地是：http， 线上是：https   接口文档地址：https://market.aliyun.com/products/57126001/cmapi021863.html#sku=yuncode1586300000
        $url = "http://wuliu.market.alicloudapi.com/kdi?$querys";

       

        //初始化curl对象
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET"); //设置GET请求
        curl_setopt($curl, CURLOPT_URL, $url); //设置请求地址
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); //设置头信息
        curl_setopt($curl, CURLOPT_FAILONERROR, false);  //不显示错误信息
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); //将结果return 回来
        curl_setopt($curl, CURLOPT_HEADER, false); //返回头信息
       
        //发送请求，并返回结果
        $output = curl_exec($curl);

        //将json 转换为 php 数组
        $output = json_decode($output, true);

        if (empty($output) || $output['status'] != 0 ) {
            $success['result'] = false;
            $success['msg'] = $output['msg'] ?? '未查询到物流信息';
            return $success;
        } else {
            $success['result'] = true;
            $success['msg'] = '查询物流信息成功';
            $success['data'] = $output['result']['list'];
        }
        return $success;
    }
}

// 多图上传
if (!function_exists('uploads')) {
    /**
     * 多图上传
     * @param String $name 字段名
     * @return Array       上传文件结果数组
     */
    function uploads($name, Request $request)
    {
        try {
            // 接收到所有的图片
            $files = $request->file($name);

            // 定义一个空的数组
            $List = [];

            foreach ($files as $item) {

                if ($item->isValid()) {

                    //获取文件的扩展名 
                    $ext = $item->getClientOriginalExtension();

                    //获取文件的绝对路径
                    $path = $item->getRealPath();

                    //定义文件名  
                    $filename =  date('Ymdhis') . \Illuminate\Support\Str::random(10) . '.' . $ext;

                    //存储文件。disk里面的public。总的来说，就是调用disk模块里的public配置
                    $path = Storage::disk('uploads')->put($filename, file_get_contents($path));

                    // 把\替换/
                    $FileName = '/uploads/' . $filename;

                    $List[] = $FileName;
                }
            }
            
            if (count($List) > 0) {
                // 返回结果
                return ['code' => 1, 'msg' => $List];
            }
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => $e->getMessage()];
        }
    }
}


if(!function_exists('httpRequest'))
{
    /**
     * curl请求函数
     * @param string $url 请求地址
     * @param array $data 请求参数
    */
    function httpRequest($url, $data = null)
    {
        if (function_exists('curl_init')) {
            // 初始化
            $curl = curl_init();
            
            // 设置请求地址
            curl_setopt($curl, CURLOPT_URL, $url);

            // 设置http某些配置
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
            
            // 判断传进来的参数是否不为空
            if (!empty($data)) {
                // 设置该请求为POST
                curl_setopt($curl, CURLOPT_POST, 1);
                // 把参数带入请求
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }

            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            $output = curl_exec($curl);
            curl_close($curl);
            return $output;
        } else {
            return false;
        }
    }
}